#!/usr/bin/env python
#
# The MIT License
#
# Copyright (c) 2008 Nicholas Galbreath
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

import os
import sys
import boto
from boto.ec2.connection import EC2Connection

def ec2start(ami, keyname, min_i=1,max_i=1):
    """
    @param ami 
    @param keyname of keys already uploaded to ami
    @param min_i minimum number of instances to start
    @param max_i minimum number of instances to start
    """
    if ami is None:
        raise Exception("ami is bogus")

    ami = unicode(ami)
    ec2_conn = boto.connect_ec2()
    images = ec2_conn.get_all_images(image_ids=[ami])

    reservation = images[0].run(min_i, max_i, keyname)

    print reservation
    print reservation.instances
    return 0

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', '--ami', dest='ami', default=None,
                      help='ami id')
    parser.add_option('-k', '--key', dest='key', default=None,
                      help = 'SSH ID')

    options, args = parser.parse_args()

    key = options.key
    if key is None:
        key = os.environ.get('EC2_SSH_KEY', None)

    if key is None:
        sys.stderr.write("Must specify key with --key " + \
                         "or env var EC2_SSH_KEY\n\n")
        sys.exit(1)
    e = ec2start(options.ami, key)
    sys.exit(e)
